package com.stormrage.edu.ctrl.edu;

import java.util.List;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.alibaba.fastjson.JSON;
import com.stormrage.constants.ErrCons;
import com.stormrage.edu.serv.adm.AdmAcctServ;
import com.stormrage.edu.serv.edu.EduMajorServ;
import com.stormrage.edu.serv.edu.EduModuleServ;
import com.stormrage.edu.serv.edu.view.EduMajorModuleServ;
import com.stormrage.entity.adm.AdmRes;
import com.stormrage.entity.edu.EduMajor;
import com.stormrage.entity.edu.rep.EduModuleRep;
import com.stormrage.entity.edu.req.EduMajorReq;
import com.stormrage.entity.edu.req.EduModuleReq;
import com.stormrage.entity.edu.view.EduMajorModule;
import com.stormrage.entity.rep.ErrorRep;
import com.stormrage.entity.rep.JsonRep;
import com.stormrage.entity.rep.ListRep;
import com.stormrage.entity.shiro.ShiroAcct;
import com.stormrage.shiro.bind.CurrentUser;
import com.stormragetech.core.ctrl.BaseCtrl;
import com.stormragetech.core.entity.Page;
import com.stormragetech.core.exception.StormrageTechException;

@Controller
@RequestMapping("/major")
public class EduMajorCtrl extends BaseCtrl {

	private static final Logger logger = LoggerFactory.getLogger(EduMajorCtrl.class);

	@Value("#{constants['html.title']}")
	private String htmlTitle;

	@Autowired
	private AdmAcctServ admAcctServ;

	@Autowired
	private EduMajorServ eduMajorServ;

	@Autowired
	private EduMajorModuleServ eduMajorModuleServ;

	@Autowired
	private EduModuleServ eduModuleServ;

	@RequiresPermissions("major:create")
	@RequestMapping(value = "/create", method = RequestMethod.GET)
	public String create(@CurrentUser ShiroAcct curr, Model model) {

		logger.debug(" 【 Controller 】-【 EduMajorCtrl 】-【 Create 】-【 GET 】- 开始运行 ");

		try {

			// ------------------ 获取用户操作的 Menu ------------------
			List<AdmRes> menus = admAcctServ.queryMenuById(Integer.valueOf(curr.getId()));

			// ------------------ Ctrl操作 ------------------
			model.addAttribute("user", curr);
			model.addAttribute("menus", menus);
			model.addAttribute("htmlTitle", htmlTitle);

		} catch (Exception e) {
			model.addAttribute("err", e.getMessage());
			return "error/500";
		}

		logger.debug(" 【 Controller 】-【 EduMajorCtrl 】-【 Create 】-【 GET 】- 结束运行 ");
		return "edu/major/create";

	}

	@RequiresPermissions("major:create")
	@RequestMapping(value = "/create", method = RequestMethod.POST)
	public String create(@CurrentUser ShiroAcct curr, EduMajor entity, RedirectAttributes redirect) {

		logger.debug(" 【 Controller 】-【 EduMajorCtrl 】-【 Create 】-【 POST 】- 开始运行 ");

		ErrorRep err = null;
		String errMsg = "";

		try {

			// ------------------ Ctrl操作 ------------------

			Integer index = eduMajorServ.create(entity);
			errMsg = "提示信息：添加编号为【 " + index + " 】专业成功";
			err = ErrorRep.instance(true, errMsg);
			redirect.addFlashAttribute("err", err);

		} catch (Exception e) {
			errMsg = "提示信息：添加专业失败";
			err = ErrorRep.instance(false, errMsg);
			redirect.addFlashAttribute("err", err);
			return "redirect:/major/list";
		}

		logger.debug(" 【 Controller 】-【 EduMajorCtrl 】-【 Create 】-【 POST 】- 结束运行 ");
		return "redirect:/major/list";

	}

	@RequiresPermissions("major:edit")
	@RequestMapping(value = "/edit/{id}", method = RequestMethod.GET)
	public String edit(@CurrentUser ShiroAcct curr, @PathVariable("id") Integer id, Model model) {

		logger.debug(" 【 Controller 】-【 EduMajorCtrl 】-【 Edit 】-【 GET 】- 开始运行 ");

		try {

			// ------------------ 获取用户操作的 Menu ------------------
			List<AdmRes> menus = admAcctServ.queryMenuById(Integer.valueOf(curr.getId()));

			// ------------------ Ctrl操作 ------------------
			EduMajor entity = eduMajorServ.queryById(id);

			model.addAttribute("user", curr);
			model.addAttribute("menus", menus);
			model.addAttribute("htmlTitle", htmlTitle);
			model.addAttribute("data", entity);

		} catch (Exception e) {
			model.addAttribute("err", e.getMessage());
			return "error/500";
		}

		logger.debug(" 【 Controller 】-【 EduMajorCtrl 】-【 Edit 】-【 GET 】- 结束运行 ");
		return "edu/major/edit";

	}

	@RequiresPermissions("major:edit")
	@RequestMapping(value = "/edit/{id}", method = RequestMethod.POST)
	public String edit(@CurrentUser ShiroAcct curr, @RequestParam(value = "majorname", required = true) String major,
			EduMajor req, RedirectAttributes redirect) {

		logger.debug(" 【 Controller 】-【 EduMajorCtrl 】-【 Edit 】-【 POST 】- 开始运行 ");

		ErrorRep err = null;
		String errMsg = "";

		req.setMajor(major);
		logger.debug(" edit请求为 " + req.toString());

		try {

			// ------------------ Ctrl操作 ------------------
			eduMajorServ.update(req);
			errMsg = "提示信息：修改编号为【 " + req.getId() + " 】专业成功";
			err = ErrorRep.instance(true, errMsg);
			redirect.addFlashAttribute("err", err);

		} catch (Exception e) {
			errMsg = "提示信息：修改专业失败";
			err = ErrorRep.instance(false, errMsg);
			redirect.addFlashAttribute("err", err);
			return "redirect:/major/list";
		}

		logger.debug(" 【 Controller 】-【 EduMajorCtrl 】-【 Edit 】-【 POST 】- 结束运行 ");
		return "redirect:/major/list";

	}

	@RequiresPermissions("major:del")
	@RequestMapping(value = "/del/{id}", method = RequestMethod.GET)
	public String delete(@CurrentUser ShiroAcct curr, @PathVariable("id") Integer id, RedirectAttributes redirect) {

		logger.debug(" 【 Controller 】-【 EduMajorCtrl 】-【 Delete 】-【 GET 】- 开始运行 ");

		ErrorRep err = null;
		String errMsg = "";

		try {

			// ------------------ Ctrl操作 ------------------
			eduMajorServ.delete(id);
			errMsg = "提示信息：删除编号为【 " + id + " 】专业成功";
			err = ErrorRep.instance(true, errMsg);
			redirect.addFlashAttribute("err", err);

		} catch (Exception e) {
			errMsg = "提示信息：删除专业失败";
			err = ErrorRep.instance(false, errMsg);
			redirect.addFlashAttribute("err", err);
			return "redirect:/major/list";
		}

		logger.debug(" 【 Controller 】-【 EduMajorCtrl 】-【 Delete 】-【 GET 】- 结束运行 ");
		return "redirect:/major/list";

	}

	@RequiresPermissions("major:view")
	@RequestMapping(value = "/list")
	public String list(@CurrentUser ShiroAcct curr, EduMajorReq req, Model model) {

		logger.debug(" 【 Controller 】-【 EduMajorCtrl 】-【 Edit 】-【 POST 】- 开始运行 ");

		try {

			// ------------------ 获取用户操作的 Menu ------------------
			List<AdmRes> menus = admAcctServ.queryMenuById(Integer.valueOf(curr.getId()));

			// ------------------ Ctrl操作 ------------------
			String search = JSON.toJSONString(req);

			logger.debug(" 查询条件req变为search为 " + search);

			if (null != search && search.length() > 0)
				model.addAttribute("search", search);

			model.addAttribute("user", curr);
			model.addAttribute("menus", menus);
			model.addAttribute("htmlTitle", htmlTitle);

		} catch (Exception e) {
			model.addAttribute("err", e.getMessage());
			return "error/500";
		}

		logger.debug(" 【 Controller 】-【 EduMajorCtrl 】-【 Edit 】-【 GET 】- 结束运行 ");
		return "edu/major/list";
	}

	@RequiresPermissions("major:view")
	@RequestMapping(value = "/ajax", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String ajax(@RequestParam(value = "draw", required = true) Integer draw,
			@RequestParam(value = "start", required = true) Integer start,
			@RequestParam(value = "length", required = true) Integer length, EduMajorReq req) {

		logger.debug(" 【 Controller 】- 【 EduMajorCtrl 】- 【 Ajax 】-【 POST 】-【 STARTED 】");

		String json = null;

		try {

			// ------------------ 获取初始化模块的状态 ------------------
			Page page = Page.instance(start, length, 1);
			req.setPage(page);
			draw += 1;

			logger.debug(" 分页信息为 " + page.toString());

			ListRep entity = eduMajorServ.queryList(req);

			JsonRep rep = JsonRep.instance(entity.getCount(), draw, entity.getList());
			json = JSON.toJSONString(rep);

		} catch (Exception e) {
			return "error/500";
		}

		logger.debug(" 返回的json为 " + json);
		logger.debug(" 【 Controller 】- 【 EduMajorCtrl 】- 【 Ajax 】-【 POST 】-【 COMPLETED 】");
		return json;

	}

	/// -------------------------------------------------- ///
	/// ------------------ 已包含模组列表 ------------------ ///
	/// -------------------------------------------------- ///
	@RequiresPermissions("course:view")
	@RequestMapping(value = "/list/{id}")
	public String list(@CurrentUser ShiroAcct curr, @PathVariable("id") Integer id, Model model) {

		logger.debug(" 【 Controller 】-【 EduMajorCtrl 】-【 List Module 】-【 GET 】- 开始运行 ");

		try {

			// ------------------ 获取用户操作的 Menu ------------------
			List<AdmRes> menus = admAcctServ.queryMenuById(Integer.valueOf(curr.getId()));

			// ------------------ Ctrl操作 ------------------
			List<EduModuleRep> array = eduModuleServ.queryRepListById(id);
			if (null != array && array.size() > 0)
				model.addAttribute("data", array);

			model.addAttribute("user", curr);
			model.addAttribute("menus", menus);
			model.addAttribute("htmlTitle", htmlTitle);

			model.addAttribute("id", id);

		} catch (Exception e) {
			model.addAttribute("err", e.getMessage());
			return "error/500";
		}

		logger.debug(" 【 Controller 】-【 EduMajorCtrl 】-【 List Module 】-【 GET 】- 结束运行 ");
		return "edu/major/mod/list";
	}

	@RequiresPermissions("course:view")
	@RequestMapping(value = "/mod/del/{cid}/{id}")
	public String deleteView(@CurrentUser ShiroAcct curr, @PathVariable("cid") Integer cid,
			@PathVariable("id") Integer id, RedirectAttributes redirect) {

		logger.debug(" 【 Controller 】-【 EduMajorCtrl 】-【 DeleteView 】-【 GET 】- 开始运行 ");

		ErrorRep err = null;
		String errMsg = "";

		try {

			// ------------------ 判断是否允许删除章节 ------------------
			EduMajor major = eduMajorServ.queryById(cid);
			if (null != major.getModule() && major.getModule().equals(0)) {

				StormrageTechException exception = StormrageTechException.instance(ErrCons.CTRL_ERR,
						"提示信息：编号为【 " + id + " 】的专业只包含唯一模组，不能删除此模组", StormrageTechException.ERR_APP,
						"【 EduMajorCtrl 】-【 DeleteView 】");

				err = ErrorRep.instance(false, exception.getMessage());
				redirect.addFlashAttribute("err", err);

				return "redirect:/major/list/{cid}";

			}

			// ------------------ Ctrl操作 ------------------
			eduMajorModuleServ.deleteById(id);
			errMsg = "提示信息：删除编号为【 " + id + " 】的专业模组关联成功";
			err = ErrorRep.instance(true, errMsg);
			redirect.addFlashAttribute("err", err);

		} catch (Exception e) {
			errMsg = "提示信息：删除【 " + id + " 】的专业模组关联失败";
			err = ErrorRep.instance(false, errMsg);
			redirect.addFlashAttribute("err", err);
			return "redirect:/major/list/{cid}";
		}

		logger.debug(" 【 Controller 】-【 EduMajorCtrl 】-【 DeleteView 】-【 GET 】- 结束运行 ");
		return "redirect:/major/list/{cid}";

	}

	@RequiresPermissions("course:view")
	@RequestMapping(value = "/mod/add/{id}")
	public String list(@CurrentUser ShiroAcct curr, EduModuleReq req, @PathVariable("id") Integer id, Model model,
			RedirectAttributes redirect) {

		logger.debug(" 【 Controller 】-【 EduMajorCtrl 】-【 List Module Except 】-【 GET 】- 开始运行 ");

		ErrorRep err = null;

		try {

			// ------------------ 判断是否允许添加章节 ------------------
			EduMajor major = eduMajorServ.queryById(id);

			logger.debug(" Major Service 专业模组唯一性为 " + major.getModule());

			if (major.getModule().equals(0)) {

				StormrageTechException exception = StormrageTechException.instance(ErrCons.CTRL_ERR,
						"提示信息：编号为【 " + id + " 】的专业只包含唯一模组，不能增加其他模组", StormrageTechException.ERR_APP,
						"【 EduMajorCtrl 】-【 DeleteView 】");

				err = ErrorRep.instance(false, exception.getMessage());
				redirect.addFlashAttribute("err", err);

				return "redirect:/major/list/{id}";

			}

			// ------------------ 获取用户操作的 Menu ------------------
			List<AdmRes> menus = admAcctServ.queryMenuById(Integer.valueOf(curr.getId()));

			// ------------------ Ctrl操作 ------------------
			String search = JSON.toJSONString(req);

			logger.debug(" 查询条件req变为search为 " + search);

			if (null != search && search.length() > 0)
				model.addAttribute("search", search);

			model.addAttribute("user", curr);
			model.addAttribute("menus", menus);
			model.addAttribute("htmlTitle", htmlTitle);

			model.addAttribute("form", req);
			model.addAttribute("id", id);

		} catch (Exception e) {
			model.addAttribute("err", e.getMessage());
			return "error/500";
		}

		logger.debug(" 【 Controller 】-【 EduMajorCtrl 】-【 List Module Except 】-【 GET 】- 结束运行 ");
		return "edu/major/mod/add";

	}

	@RequiresPermissions("course:view")
	@RequestMapping(value = "/mod/ajax/{id}", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String ajax(@RequestParam(value = "draw", required = true) Integer draw,
			@RequestParam(value = "start", required = true) Integer start,
			@RequestParam(value = "length", required = true) Integer length, @PathVariable("id") Integer id,
			EduModuleReq req) {

		logger.debug(" 【 Controller 】- 【 EduMajorCtrl 】- 【 Ajax Module 】-【 POST 】-【 STARTED 】");

		String json = null;

		try {

			// ------------------ 获取初始化模块的状态 ------------------
			Page page = Page.instance(start, length, 1);
			req.setPage(page);
			draw += 1;

			logger.debug(" 分页信息为 " + page.toString());

			ListRep entity = eduModuleServ.queryList(id, req);

			JsonRep rep = JsonRep.instance(entity.getCount(), draw, entity.getList());
			json = JSON.toJSONString(rep);

		} catch (Exception e) {
			return "error/500";
		}

		logger.debug(" 返回的json为 " + json);
		logger.debug(" 【 Controller 】- 【 EduMajorCtrl 】- 【 Ajax Module 】-【 POST 】-【 COMPLETED 】");
		return json;

	}

	@RequiresPermissions("course:edit")
	@RequestMapping(value = "/mod/add/{cid}/{id}")
	public String add(@CurrentUser ShiroAcct curr, @PathVariable("cid") Integer cid, @PathVariable("id") Integer id,
			RedirectAttributes redirect) {

		logger.debug(" 【 Controller 】-【 EduMajorCtrl 】-【 Add 】-【 GET 】- 开始运行 ");

		ErrorRep err = null;
		String errMsg = "";

		try {

			// ------------------ Ctrl操作 ------------------
			EduMajorModule entity = EduMajorModule.instance(cid, id);
			eduMajorModuleServ.create(entity);

			errMsg = "提示信息：编号为【 " + cid + " 】的专业关联编号为【 " + id + " 】的模组成功";
			err = ErrorRep.instance(true, errMsg);
			redirect.addFlashAttribute("err", err);

		} catch (Exception e) {
			errMsg = "提示信息：编号为【 " + cid + " 】的专业关联编号为【 " + id + " 】的模组失败";
			err = ErrorRep.instance(false, errMsg);
			redirect.addFlashAttribute("err", err);
			return "redirect:/major/mod/add/{cid}";
		}

		logger.debug(" 【 Controller 】-【 EduMajorCtrl 】-【 Add 】-【 GET 】- 结束运行 ");
		return "redirect:/major/mod/add/{cid}";

	}

}
